package com.iweb.user.service;

import com.iweb.user.dao.UserOrderMapper;
import com.iweb.user.dao.UserRefundMapper;
import com.iweb.user.dao.UserSeatMapper;
import com.iweb.user.model.Order;
import com.iweb.user.model.Refund;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;

@Service
public class UserRefundServiceImpl implements UserRefundService {

    @Autowired
    private UserOrderMapper userOrderMapper;

    @Autowired
    private UserRefundMapper userRefundMapper;

    @Autowired
    private UserSeatMapper userSeatMapper;

    @Override
    @Transactional
    public String processRefund(long orderId) {
        Order order = userOrderMapper.selectById(orderId);
        if (order == null) {
            return "退票失败：订单不存在。";
        }
        if (!"已付款".equals(order.getStatus())) {
            return "退票失败：该订单不是“已付款”状态，无法退款。";
        }

        Refund existingRefund = userRefundMapper.selectByOrderId(orderId);
        if (existingRefund != null) {
            return "退票失败：该订单已处理过退款，请勿重复提交。";
        }

        Refund refund = new Refund();
        refund.setOrderId(order.getOrderId());
        refund.setUserId(order.getUserId());
        refund.setShowName(order.getShowName());
        refund.setPrice(order.getPrice());
        refund.setCreateTime(new Date());
        userRefundMapper.insert(refund);

        int updatedRows = userOrderMapper.updateStatus(orderId, "已退款");
        if (updatedRows == 0) {
            throw new RuntimeException("退票失败：数据库更新订单状态失败。事务将回滚。");
        }

        userSeatMapper.updateStatusToAvailable(order.getSeatId());

        return "退票成功！订单 " + orderId + " 已被标记为已退款。";
    }
}
